import { createSlice } from "@reduxjs/toolkit";
import { setToken as setTokenUtil, getToken, removeToken } from "@/utils";
import { loginApi, getUserInfoApi } from "@/apis/user";

const userStore = createSlice({
    name: "user",
    initialState: {
        token: getToken() || '',
        userInfo: {},
    },
    reducers: {
        setToken: (state, action) => {
            state.token = action.payload;
            setTokenUtil(action.payload);
        },
        setUserInfo: (state, action) => { state.userInfo = action.payload; },
        clearUserInfo: (state) => { 
            state.userInfo = {}; 
            removeToken();
            console.log("清除用户信息");
        },
    }
})

const { setToken, setUserInfo,clearUserInfo} = userStore.actions;

// 异步方法
const setTokenAsync = (loginForm) => {
    return async (dispatch) => {
        const res = await loginApi(loginForm);
        // console.log(res);
        dispatch(setToken(res.data.token));
    }
}

const setUserInfoAsync = () => { 
    return async (dispatch) => { 
        const res = await getUserInfoApi();
        console.log(res);
        dispatch(setUserInfo(res.data)); 
    } 
}

export {setToken, setTokenAsync, setUserInfo, setUserInfoAsync, clearUserInfo};

const userReducer = userStore.reducer;
export default userReducer;